<template>
	<div>
		<div ref="biaotou">
			<el-form inline :model="formData">
				<el-row>
					<el-col :span="24">
						<el-form-item label="单据状态:">
							<el-select v-model="formData.status" clearable>
								<el-option :value="0" label="待审核"></el-option>
								<el-option :value="1" label="审批完成"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="报销单号">
							<el-input v-model="formData.reimNumber" placeholder="请输入报销单号"></el-input>
						</el-form-item>
						<el-form-item label="报销类别">
							<el-select v-model="formData.reimType" style="width: 100%;"  clearable filterable>
								<el-option v-for="(item,index) in ResEnum" :value="item.Value"
									:label="item.Description"></el-option>
							</el-select>							
						</el-form-item>
						<el-form-item label="申报人">
							<el-select v-model="formData.borrower" style="width: 100%;"  clearable filterable>
								<el-option v-for="(item,index) in $store.state.AllUsers" :value="item.Id"
									:label="item.UserName" v-if="item.RoleId != '1'"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="月份筛选">
							<el-date-picker style="width: 99%;" type="month" v-model="formData.month" @change="monthChange" placeholder="选择月份">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="开始时间">
							<el-date-picker style="width: 99%;" v-model="formData.startTime" value-format="yyyy-MM-dd" placeholder="选择开始日期">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="结束时间">
							<el-date-picker style="width: 99%;" v-model="formData.endTime" value-format="yyyy-MM-dd" placeholder="选择结束日期">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="年份" v-if="$store.state.user.roleid == '1'">
							<el-date-picker type="year" v-model="formData.settlementNumber" value-format="yyyy"  filterable clearable></el-date-picker>
						</el-form-item>
						<el-form-item label="">
							<el-checkbox style="width:100%" v-model="formData.IsDelete" label="已删除单据" border></el-checkbox>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="getTableData">查询</el-button>
						</el-form-item>
						<el-form-item>
							<el-button type="success" @click="ApplyAdddialog.show = true"
								:disabled="project.ProjectStatus == 1">新建报销单</el-button>
						</el-form-item>
					</el-col>
				</el-row>
				<!-- <el-row>
					<el-col :span="24">
						<el-form-item>
							<el-button type="success" @click="ApplyAdddialog.show = true"
								:disabled="project.ProjectStatus == 1">新建</el-button>
							<el-tooltip class="item" effect="dark" content="年度开账将结算上一年度数据" placement="right">
								<el-button type="primary" icon="el-icon-s-check"
									@click="UpSettlementDialog">年度开账</el-button>
							</el-tooltip>
						</el-form-item>
					</el-col>
				</el-row> -->
			</el-form>
		</div>
		<div>
			<el-table v-loading="pagination.tableloading" :height="tableStyle+'px'" :data="payrollList" border show-summary :summary-method="getSummaries" @select="tableSelectEvent"
				@select-all="tableSelectEvent">
				<el-table-column type="selection" width="42" align="center"></el-table-column>
				<el-table-column type="index" label="序号" width="50" align="center"
					:index="indexMethod"></el-table-column>
				<el-table-column label="报销单号" align="center" prop="ReimNumber">
					<template slot-scope="scope">
						{{ scope.row.fina.ReimNumber }}
					</template>
				</el-table-column>
				<el-table-column label="报销类别" align="center" prop="ConstructionType">
					<template slot-scope="scope">
						{{ getDataMessage('Res',scope.row) }}
					</template>
				</el-table-column>
				<el-table-column label="申报人" align="center" prop="UserId">
					<template slot-scope="scope">
						{{ getDataMessage('User',scope.row) }}
					</template>
				</el-table-column>
				<el-table-column label="申报时间" align="center" prop="BorrowTime">
					<template slot-scope="scope">
						{{ timeformat(scope.row.fina.BorrowTime) }}
					</template>
				</el-table-column>
				<el-table-column label="报销金额(元)" align="center" prop="Mony">
					<template slot-scope="scope">
						{{ scope.row.Mony }}
					</template>
				</el-table-column>
				<el-table-column label="审批状态" align="center" prop="FinanceReimbursementStart">
					<template slot-scope="scope">
						<p v-if="scope.row.fina.FinanceReimbursementStart == 0" style="color: #E6A23C;">待审批</p>
						<p v-else style="color: #67C23A;">审批完成</p>
					</template>
				</el-table-column>
				<el-table-column label="开账状态" align="center" prop="FinanceReimbursementStart">
					<template slot-scope="scope">
						<p v-if="scope.row.fina.Settlement" style="color: #67C23A;">
							({{ scope.row.fina.SettlementNumber }})开账 账单</p>
							<p v-else style="color: #e6a23c;">  ({{ scope.row.fina.SettlementNumber }}年度 账单)</p>
					</template>
				</el-table-column>
				<el-table-column label="附件" align="center" prop="BorrowTime">
					<template slot-scope="scope">
						<el-button type="text" @click="DownUserId(scope.row)">下载</el-button>
						<el-button type="text" size="mini" @click="PreviewImageEvent(scope.row)"
							style="margin-left: 10px;color: #E6A23C;">预览</el-button>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" width="330">
					<template slot-scope="scope">
						<el-button plain type="primary" size="mini" @click="getApplyDetails(scope.row)"
							style="margin-left: 10px;">详情</el-button>
						<el-button plain type="primary" size="mini" @click="OpenSettlementDialog(scope.row)" >年度开账</el-button>
						<br>
						<div style="margin-top:10px">
							<el-popover placement="right" width="400" trigger="click" style="margin-right: 10px;">
							<UploadFileF ref="AnotherData" :multiple="true" :another-data="AnotherData"
								:showfilelist="true" :upshow="true" content="上传文件" btnsize="medium"></UploadFileF>
							<el-button plain type="primary" slot="reference" size="mini" 
								@click="AnotherData.id = scope.row.fina.Id">附件上传</el-button>
							</el-popover>
							<el-button plain type="info" size="mini"
								@click="GetFormFinanceReimExcel(scope.row)">导出</el-button>
							<el-popconfirm title="这是一段内容确定删除吗" @confirm="deleteDetails(scope.row)"
								style="padding-left: 10px;">
								<el-button slot="reference" plain type="danger" size="mini"
									:disabled="project.ProjectStatus == 1">删除</el-button>
							</el-popconfirm>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-row>
				<el-col :span="24" align="right">
					<el-pagination @size-change="getTableData" @current-change="getTableData"
						:current-page.sync="pagination.currentPage" :page-sizes="pagination.pagesizes"
						:page-size.sync="pagination.pagesize" layout="total, sizes, prev, pager, next, jumper"
						:total.sync="pagination.total">
					</el-pagination>
				</el-col>
			</el-row>
		</div>

		<el-dialog :visible.sync="ApplyAdddialog.show" title="新增报销单" width="90%" :append-to-body='true'
			@close="ApplyAddRefEvent()">
			<ApplyAdd :project="project" :closeFun="childrenCloseEvent" ref="ApplyAddRef"></ApplyAdd>
		</el-dialog>

		<el-dialog :visible.sync="ApplyFormdialog.show" title="编辑报销单" width="90%" :append-to-body='true'
			@close="ApplyFormRefEvent()">
			<ApplyForm :project="project" :closeFun="childrenCloseEvent" :ApplyDetalis="ApplyFormdialog.ApplyDetalis"
				ref="ApplyFormRef">
			</ApplyForm>
		</el-dialog>

		<el-dialog append-to-body title="提示" :visible.sync="kaizhangDialog.show" width="30%"
			@close="dialogVisibleEvent">
			<div style="display: flex;flex-direction: column;gap: 10px;">
				<span>你确定要开账此选择吗?</span>
				<div>
					开帐年份：<el-date-picker v-model="kaizhangDialog.SettlementNumber" type="year" value-format="yyyy"
						placeholder="选择年份" @change="SettlementNumberEvent"></el-date-picker>
				</div>
				<div v-if="CheckSettlementResult.StatusCode == 500 && CheckSettlementResult.Message!=''">
					<p style="color: #E6A23C;margin:5px 0px !important; ">{{ CheckSettlementResult.Message }}</p>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleEvent">取 消</el-button>
				<el-button type="primary" @click="IsUpSettlementHandlerNew(false)">确 定</el-button>
			</span>
		</el-dialog>

		<el-image-viewer v-if="showViewer" :on-close="() => { showViewer = false }" :url-list="imgArray"
			style="z-index: 300000;" />

	</div>
</template>

<script>
	import {
		Message,
		Switch
	} from 'element-ui'
	import ApplyAdd from './ApplyAdd.vue'
	import ApplyForm from './ApplyForm.vue'
	import * as publicjs from "../../../../public/Scriput/Public"
	import UploadFileF from "../../UploadFileF";
	import dayjs from 'dayjs';
	export default {
		components: {
			ApplyAdd,
			ApplyForm,
			UploadFileF,
			'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
		},
		props: {
			project: {
				type: Object,
				required: true
			}
		},
		data() {
			return {
				ResEnum: [],
				payrollList: [],
				formData: {
					status: 0,
					reimType:'',
					borrower:'',
					//month: dayjs().format('YYYY-MM-DD'),
					//startTime: dayjs().startOf('month').format('YYYY-MM-DD'),
					//endTime: dayjs().format('YYYY-MM-DD'),
					month: '',
					startTime: '',
					endTime: '',
					reimNumber:'',
					settlementNumber: '',
					IsDelete: false,
				},
				LoanRes: [],
				ApplyAdddialog: {
					show: false,
				},
				ApplyFormdialog: {
					ApplyDetalis: {},
					show: false,
				},
				AnotherData: {
					//项目模块
					FileType: 512,
					//项目Id号
					id: 0,
					//Type：1：收方工资单  2、应发工资单、3报销单 
					Type: 3,
					Single: false,
				},
				tableSelectRows: [],
				kaizhangDialog: {
					show: false,
					SettlementNumber: '',
					clickrow:[],
				},
				CheckSettlementResult: {
					Status: true,
					Message: '',
					StatusCode: 200
				},
				//图片预览集合
				imgArray: [],
				showViewer: false,
				tableStyle:500,
				//分页数据绑定
				pagination: {
					currentPage: 1,
					pagesizes: [10, 50, 100, 300, 500],
					pagesize: 10,
					total: 0,
					tableloading: false
				},
			}
		},
		created() {
			publicjs.http(this.$http, this.$message)
		},
		mounted() {
			this.getTableData()
			this.GetFinanceLoanResEnum()
			window.addEventListener('resize',()=>{
				this.tableHeightJiSuan()
			})
		},
		methods: {
			//表格序号
			indexMethod(index) {
				return index + 1
			},
			//申报类型数据
			GetFinanceLoanResEnum() {
				this.$http.post('NewFinanceReimbursementReim/GetFinanceLoanResEnum').then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) {
						this.ResEnum = Data
					} else {
						this.ResEnum = []
					}
				})
			},
			//页面初始数据获取
			getTableData() {
				const {
					Id: ProjectId
				} = this.project || null
				if (ProjectId != null) {
					this.pagination.tableloading = true
					let params = {
						Id: ProjectId,
						Status: this.formData.status,
						ReimNumber: this.formData.reimNumber == ''? null:this.formData.reimNumber,
						Borrower: this.formData.borrower == ''? 0:this.formData.borrower,
						ReimType: this.formData.reimType == ''?0:this.formData.reimType,
						StartTime: (this.formData.startTime == '' || this.formData.startTime == null)?null:this.formData.startTime+'T00:00:00.000Z',
						EndTime: (this.formData.endTime == '' || this.formData.endTime == null)?null:this.formData.endTime+'T23:59:59.000Z',
						SettlementNumber: this.formData.settlementNumber,
						IsDelete:this.formData.IsDelete,
						pageSize: this.pagination.pagesize,
						pageIndex: this.pagination.currentPage,
					}
					this.$http.post('NewFinanceReimbursementReim/SelHDFinanceReimbursement', params).then(res => {
						const {
							StatusCode,
							Data,
							TotalCount,
						} = res.data || 0
						if (StatusCode == 200) {
							this.payrollList = Data
						} else {
							this.payrollList = []
							this.$message.warning('获取项目申报单失败,请重试!')
						}
						this.tableHeightJiSuan()
						this.pagination.total = TotalCount
						this.pagination.tableloading = false
					}).catch(()=>{ this.pagination.tableloading = false })
				} else {
					this.$message.warning('获取项目申报单失败!')
				}
			},
			//获取数据描述
			getDataMessage(type, row) {
				const {
					FinanceReimbursementReimType,
					UserId
				} = row.fina || null
				let messaga = ''
				let Obj = undefined
				switch (type) {
					case 'Res':
						Obj = this.ResEnum.find(x => x.Value == FinanceReimbursementReimType)
						if (Obj != undefined) messaga = Obj.Description
						break;
					case 'User':
						Obj = this.$store.state.AllUsers.find(x => x.Id == UserId)
						if (Obj != undefined) messaga = Obj.UserName
						break;
				}
				return messaga
			},
			//子窗口关闭调用
			childrenCloseEvent() {
				this.ApplyAdddialog.show = false
				this.ApplyFormdialog.show = false
				this.getTableData()
			},
			//删除申报单
			deleteDetails(row) {
				this.$http.post('NewFinanceReimbursementReim/DelHDFinanceReimbursement', {
					Id: row.fina.Id
				}).then(res => {
					const {
						StatusCode,
						Data
					} = res.data || 0
					if (StatusCode == 200) {
						this.$message.success('删除成功')
					} else {
						this.$message.warning('删除失败,请重试!')
					}
					this.getTableData()
				})
			},
			//获取申报单详情
			getApplyDetails(row) {
				this.ApplyFormdialog.show = true
				this.ApplyFormdialog.ApplyDetalis = row
			},
			//数据导出
			GetFormFinanceReimExcel(row) {
				this.$http.post('NewFinanceReimbursementReim/GetFormFinanceReimExcel', {
					ProjectId: this.project.Id,
					id: row.fina.Id,
				}).then(res => {
					const {
						StatusCode,
						Data,
						Message
					} = res.data || 0
					if (StatusCode == 200) {
						//文件下载
						publicjs.DownLoadFile({
							...Data
						})
					} else {
						this.$message.warning(Message)
					}
				})
			},
			//下载文件
			DownUserId(row) {
				let Data = {
					id: row.fina.Id || row.fina.id,
					FileType: 512,
					Type: 3,
					FileName: '',
				}
				//文件下载
				publicjs.DownLoadFile({
					...Data
				})
			},
			//添加弹框关闭
			ApplyAddRefEvent() {
				this.$refs.ApplyAddRef.clearFormData()
			},
			ApplyFormRefEvent() {
				this.$refs.ApplyFormRef.clearFormData()
				this.getTableData()
			},
			//项目是否完结
			projectOver() {
				const {
					EndDate
				} = this.project || ''
				if (EndDate == undefined || EndDate == '') {
					return false
				} else {
					let chazhi = dayjs(EndDate).diff(Date(), 'day')
					return chazhi < 0 ? true : false
				}
			},
			//表格选择
			tableSelectEvent(values, row) {
				this.tableSelectRows = values
			},
			//时间选择事件
			SettlementNumberEvent(value) {
				if (value == '') return
				this.$http.post('NewFinanceReimbursementReim/CheckSettlement', {
					settlementNumber: value,
					projectId: this.project.Id
				}).then(res => {
					this.CheckSettlementResult = res.data
				})
			},
			//修改已经扎帐订单,请谨慎操作
			UpSettlementDialog() {
				if (this.tableSelectRows.length == 0) {
					this.$message.warning('请选择需要年度开账的数据!')
					return
				}
				if (this.tableSelectRows.length > 1) {
					this.$message.warning('年度开账数据只能存在一条!')
					return
				}
				this.kaizhangDialog = {
					show: true,
					SettlementNumber: '2025',
				}
			},
			//点击开账按钮，打开开账对话框页面
			OpenSettlementDialog(row) {
				this.kaizhangDialog = {
					show: true,
					SettlementNumber: '2025',
					clickrow:row,
				}
			},
			//弹框关闭
			dialogVisibleEvent() {
				this.kaizhangDialog = {
					show: false,
					SettlementNumber: ''
				}
				this.CheckSettlementResult = {
					Message: '',
					StatusCode: 200
				}
			},
			//提交新开账数据
			IsUpSettlementHandler() {
				this.$http.post('NewFinanceReimbursementReim/SetSettlement', {
					settlementNumber: this.kaizhangDialog.SettlementNumber,
					orderId: this.tableSelectRows[0].fina.Id,
					projectid:this.tableSelectRows[0].fina.ProjectId
				}).then(res => {
					const {
						StatusCode,
						Data,
						Message
					} = res.data || 0
					if (StatusCode == 200) {
						this.$message.success('年度开账成功!')
						this.dialogVisibleEvent()
						this.getTableData()
					} else {
						this.$message.warning(Message)
					}
				})
			},
			//单独提交新开账数据
			IsUpSettlementHandlerNew() {
				console.log(1234);
				if(this.kaizhangDialog.SettlementNumber==""||this.kaizhangDialog.SettlementNumber==null)
				{
					this.$message.warning('开账年份不能为空，请选择开账年份！')
					return;
				}
				var row=this.kaizhangDialog.clickrow;
				this.$http.post('NewFinanceReimbursementReim/SetSettlement', {
					settlementNumber: this.kaizhangDialog.SettlementNumber,
					orderId: row.fina.Id,
					projectid:row.fina.ProjectId
				}).then(res => {
					const {
						StatusCode,
						Data,
						Message
					} = res.data || 0
					if (StatusCode == 200) {
						this.$message.success('年度开账成功!')
						this.dialogVisibleEvent()
						this.getTableData()
					} else {
						this.$message.warning(Message)
					}
				})
			},
			//预览图片
			async PreviewImageEvent(row) {
				let Data = {
					id: row.fina.Id || row.fina.id,
					FileType: 512,
					Type: 3,
					FileName: '',
				}
				let path = Data.FileType + ',' + Data.id + ',' + Data.Type
				let BasePath = this.$BasePath.substring(0, this.$BasePath.length - 1)
				//文件下载
				let imgArray = await publicjs.GetAllFileByUrl(this.$http, path)
				if (imgArray.length > 0) {
					this.imgArray = imgArray.map(x => {
						return BasePath + x
					})
					this.showViewer = true
				} else {
					this.$message.warning('暂无上传图片文件!')
					this.showViewer = false
				}
			},
			timeformat(time) {
				if (time == '' || time == null) {
					return ''
				} else {
					return dayjs(time).format('YYYY-MM-DD')
				}
			},
			//表格数据合集
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '总价';
						return;
					}
					const values = data.map(item => Number(item[column.property]));
					if (!values.every(value => isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr);
							if (!isNaN(value)) {
								let sum =  parseFloat(prev)  + parseFloat(curr)
								return sum.toFixed(2);
							} else {
								return prev.toFixed(2);
							}
						}, 0);
						sums[index] += ' 元';
					} else {
						sums[index] = '';
					}
				});
				return sums;
			},
			//月份切换
			monthChange(time){
				if(time != '' && time !=null){
					this.formData.startTime = dayjs(time).startOf('month').format('YYYY-MM-DD')
					this.formData.endTime = dayjs(time).endOf('month').format('YYYY-MM-DD')					
				}
			},
			//表格高度计算
			tableHeightJiSuan(){
				this.tableStyle = document.body.clientHeight - this.$refs.biaotou.clientHeight - 116
			},
		}
	}
</script>

<style>
</style>